package com.wyc.blog.web.admin;

import com.wyc.blog.po.User;
import com.wyc.blog.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;

/**
 * @ClassName LoginController
 * @Author 王韫琛
 * @Date 2021/4/24 20:39
 * @Version 1.0
 */
@Controller
@RequestMapping("/admin")
public class LoginController {

    @Autowired
    private IUserService userService;

    @GetMapping
    public String loginPage(){
        return "admin/login";
    }

    /**
     * 登录页面方法
     * @param username
     * @param password
     * @param session
     * @return
     */
    @PostMapping("/login")
    public String login(@RequestParam String username,
                        @RequestParam String password,
                        HttpSession session,
                        RedirectAttributes attributes){
        User user = userService.checkUser(username, password);
        if (user!=null){
            user.setPassword(null);
            session.setAttribute("user",user);
            return "admin/index";
        }else {
            attributes.addFlashAttribute("message","用户名或密码错误");
            //用Model重定向的时候信息不能携带
            return "redirect:/admin";
        }

    }

    @GetMapping("/logout")
    public String logout(HttpSession session){
        session.removeAttribute("user");
        return "redirect:/admin";
    }
}
